// pages/shop/shop.js

const config = require('../../config/config.js')
const util = require('../../utils/util.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    downArrow: "./../../imgs/down.png",
    upArrow: "./../../imgs/up.png",
    currentSel: 0,
    pageScroll: "",

    regions: [],
    regionInfos: [],
    currentSelectRegionIndex: 0,
    currentSelectRgionInfoIndex: 0,
    changeRegion: false,

    shopStyles: config.foodStyles,
    currentShopStyleIndex: 0,

    shopOrderRules: config.shopOrderRules,
    currentShopOrderRuleIndex: 0,

    regionArea: '',
    regionInfo: '',
    shopStyle: '',
    orderRule: config.shopOrderRuleMap.get(config.shopOrderRules[0]),

    currentPage: 1,
    shops: [],
    bottomLoading: false,
    alreadyBottom: false,
    startLoading: false,

    reload: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    this.initRegionsInfo()

    this.refreshing = false
    this.setData({
      startLoading: true
    })
    this.refreshShops(this.data.currentPage).then(res => {
      this.setData({
        shops: res,
        startLoading: false
      })
    })

    this.getShopStyles().then(res => {
      // console.log(res)
      if (res.code == 1) {
        let shopStyles = ['所有菜系']
        for (let i = 0, length = res.data.length; i < length; i++) {
          shopStyles.push(res.data[i].shop_style)
        }
        // console.log(shopStyles)
        this.setData({
          shopStyles: shopStyles
        })
      }
    })
  },


  getShopStyles: function () {
    return new Promise(resolve => {
      wx.request({
        url: `${config.requestBaseUrl}/Shop/getShopStyles`,
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          // console.log(res)
          resolve(res.data)
        }
      })
    })
  },

  refreshShopsInfo: function () {
    if (!this.refreshing) {
      this.setData({
        startLoading: true,
        currentPage: 1
      })
      this.refreshing = true
      this.refreshShops(this.data.currentPage).then(res => {
        this.setData({
          shops: res,
          alreadyBottom: false,
          startLoading: false,
          changeRegion: false
        })
        this.refreshing = false
      })
    }
  },

  initRegionsInfo: function() {
    this.regions = ['热门商区']
    this.regionsMap = {}
    for (let index in config.regions) {
      this.regions.push(config.regions[index])
      this.regionsMap[config.regions[index]] = [config.regions[index] + '全区'].concat(config.regionsMap[config.regions[index]])
    }
    // this.regionsMap = config.regionsMap
    this.regionsMap['热门商区'] = config.hotRegions
    // console.log(this.regionsMap)
    this.setData({
      regions: this.regions,
      regionInfos: this.regionsMap[this.regions[0]]
    })
  },

  refreshShops: function (currentPage) {
    let that = this
    return new Promise(resolve => {
      wx.getLocation({
        success: function(res) {
          wx.request({
            url: `${config.requestBaseUrl}/Shop/getShops`,
            method: 'POST',
            data: {
              latitude: res.latitude,
              longitude: res.longitude,
              page: currentPage,
              openid: wx.getStorageSync('openid'),
              area: that.data.regionArea,
              region: that.data.regionInfo,
              shop_style: that.data.shopStyle,
              order_rule: that.data.orderRule
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              // console.log(res)
              let data = res.data
              for (let i = 0, len = data.length; i < len; i++) {
                let distance = data[i]['distance']
                data[i]['distance'] = distance < 1 ? Math.round(distance * 1000) + 'm' : Math.round(distance * 10) / 10 + 'km'
              }
              resolve(data)
            }
          })
        },
        fail: function() {
          that.setData({
            startLoading: false
          })
          util.getUserLocation(function() {
            that.setData({
              reload: true,
              startLoading: false
            })
          })
        }
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.reload) {
      this.setData({
        reload: false
      })
      this.refreshing = false
      this.setData({
        startLoading: true
      })
      this.refreshShops(this.data.currentPage).then(res => {
        this.setData({
          shops: res,
          startLoading: false
        })
      })
    }

    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (!this.refreshing) {
      this.setData({
        currentPage: 1
      })
      this.refreshing = true
      this.refreshShops(this.data.currentPage).then(res => {
        this.setData({
          shops: res,
          alreadyBottom: false
        })
        this.refreshing = false
        wx.stopPullDownRefresh()
      })
    } else {
      wx.stopPullDownRefresh()
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.alreadyBottom && !this.data.bottomLoading) {
      this.setData({
        bottomLoading: true
      })
      this.refreshShops(this.data.currentPage + 1).then(res => {
        if (res.length > 0) {
          this.setData({
            shops: this.data.shops.concat(res),
            currentPage: this.data.currentPage + 1,
            bottomLoading: false
          })
        } else {
          this.setData({
            alreadyBottom: true,
            bottomLoading: false
          })
        }
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  selectItem: function(event) {
    // console.log(event.currentTarget.dataset.currentsel)
    let currentsel = event.currentTarget.dataset.currentsel
    if (currentsel === this.data.currentSel) {
      this.setData({
        pageScroll: "",
        currentSel: 0
      })
    } else {
      this.setData({
        pageScroll: "hidden",
        currentSel: currentsel
      })
    }
    
  },

  clickBackPanel: function() {
    this.setData({
      pageScroll: "",
      currentSel: 0
    })
    if (!this.data.changeRegion) {
      return
    }
    this.setData({
      regionArea: this.data.currentSelectRegionIndex == 0 ? "" : this.data.regions[this.data.currentSelectRegionIndex]
    })
    console.log(this.data.regionInfo)
    console.log(this.data.regionArea)
    this.refreshShopsInfo()
  },

  selectLocal: function(event) {
    let index = event.currentTarget.dataset.localindex
    if (index == this.data.currentSelectRegionIndex) {
      this.setData({
        changeRegion: false
      })
      return
    }
    this.setData({
      currentSelectRegionIndex: index,
      regionInfos: this.regionsMap[this.regions[index]],
      currentSelectRgionInfoIndex: 0,
      regionInfo: "",
      changeRegion: true
    })
  },

  selectShopArea: function(event) {
    let index = event.currentTarget.dataset.selectindex
    this.setData({
      currentSel: 0,
      pageScroll: "",
    })
    if (index == this.data.currentSelectRgionInfoIndex && !this.data.changeRegion) {
      return
    }
    this.setData({
      currentSelectRgionInfoIndex: index,
      regionInfo: index == 0 ? "" : this.data.regionInfos[index],
      regionArea: index == 0 ? (this.data.currentSelectRegionIndex == 0 ? "" : this.data.regions[this.data.currentSelectRegionIndex]) : ""
    })
    console.log(this.data.regionInfo)
    console.log(this.data.regionArea)
    this.refreshShopsInfo()
  },

  selectShopStyle: function (event) {
    let index = event.currentTarget.dataset.index
    this.setData({
      currentSel: 0,
      pageScroll: "",
    })
    if (index == this.data.currentShopStyleIndex) {
      return
    }
    this.setData({
      currentShopStyleIndex: index,
      shopStyle: index == 0 ? "" : this.data.shopStyles[index]
    })
    console.log(this.data.shopStyle)
    this.refreshShopsInfo()
  },

  selectShopOrderRule: function (event) {
    let index = event.currentTarget.dataset.index
    this.setData({
      currentSel: 0,
      pageScroll: "",
    })
    if (index == this.data.currentShopOrderRuleIndex) {
      return
    }
    this.setData({
      currentShopOrderRuleIndex: index,
      orderRule: config.shopOrderRuleMap.get(this.data.shopOrderRules[index])
    })
    console.log(this.data.orderRule)
    this.refreshShopsInfo()
  },

  clickCollectShop: function(event) {
    let that = this
    let shopId = event.currentTarget.dataset.id
    let index = event.currentTarget.dataset.index
    wx.request({
      url: `${config.requestBaseUrl}/Collect/CollectShop`,
      method: 'POST',
      data: {
        shop_id: shopId,
        openid: wx.getStorageSync('openid')
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        if (res.data.code != 0) {
          let shops = that.data.shops
          shops[index].is_collect = res.data.code === 1 ? 1 : 0
          that.setData({
            shops: shops
          })
        }
      }
    })
  }

})